import cv2  
import queue  
import threading    
import time   
import queue  
import threading  
from utilities.TemplateMatch import TemplateMatcher
from utilities.DeviceConect import TCPClient
from utilities.ImagePreprocess import ImageProcessor


# class MaxSizeQueue:
#     def __init__(self, maxsize):
#         self.queue = queue.Queue
#         self.maxsize = maxsize

#     def put(self, item):
#         if self.queue.qsize() >= self.maxsize:
#             self.queue.get() # throw away the oldest element
#         self.queue.put(item)

#     def get(self):
#         return self.queue.get()
    
#     def qsize(self):
#         return self.queue.qsize()
    
#     def get_nowait(self):
#         return self.queue.get_nowait()



# 线程1：处理视频流并执行模板匹配  
def process_video_stream_thread(ip='192.168.121.130', port=8900):  
    # 打开USB相机  
    cap = cv2.VideoCapture(0)  # 0通常是默认相机  
      
    # 检查相机是否成功打开  
    if not cap.isOpened():  
        print("Error opening video stream or file")  
        return  
      # TCP客户端类，负责建立连接和发送消息  
    # 设置默认尺寸（1080p）  
    default_size = (1920, 1080)  
      
    # 读取掩模版  
    # mask_template = cv2.imread('path_to_your_mask.png', cv2.IMREAD_GRAYSCALE)  

    # 每隔多少帧捕获一帧  
    frame_interval = 1  # 例如，每隔5帧捕获一帧  
    frame_counter = 0  
      
    client = TCPClient(ip, port) 

    try:  
        while True:  
            # 尝试连接  
            if not client.connected:  
                client.connect()  

            # # 读取当前帧  
            # ret, frame = cap.read()  
            # if not ret:  
            #     print("Can't receive frame (stream end?). Exiting ...")  
            #     break  
              
            # # 每隔frame_interval帧处理一次  
            # frame_counter += 1  
            # if frame_counter % frame_interval != 0:  
            #     continue  
              
            # # 调整图像尺寸  
            # resized_frame = cv2.resize(frame, default_size)  
              
            # # 应用掩模版进行二值化  
            # # _, thresholded_frame = cv2.threshold(resized_frame, 190, 255, cv2.THRESH_BINARY)  
            # # thresholded_frame = cv2.bitwise_and(thresholded_frame, thresholded_frame, mask=mask_template)  

            # red_range = [(0, 33, 0), (255, 199, 255)]  # 下限; 上限   231/239 255
            # # gray_image = cv2.cvtColor(resized_frame, cv2.RGB2GRAY)
            # # RGB_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2RGB)
            # HSV_image = cv2.cvtColor(resized_frame, cv2.COLOR_RGB2HSV)
            # thresholded_frame = cv2.inRange(HSV_image, red_range[0], red_range[1])  # 二值化处理图片

            # # Split the image into 6 part
            # processor = ImageProcessor(width=1920, height=1080)  
            # preprocessed_images = processor.img_detect(resized_frame)

              
            # 调用模板匹配接口 
            matched_chars = {
                    'SN': '651411240047',
                    'P_0': None,
                    'P_1': None,
                    'T': None,
                    'Q_0': None,
                }
            # for i in range(len(preprocessed_images)):
            for i in range(2):
                template_matcher = TemplateMatcher('image/template/', 'image/raw_image/HSV-2-Digital-4.jpg')
                # template_matcher = TemplateMatcher('image/template/', preprocessed_images[i])

                if i == 0: # Kongzhikou Pressure
                    matched_chars['P_1'] = template_matcher.process(0.7)
                elif i == 1: # Jinyouqiang Pressure No route to host
                    matched_chars['P_0'] = template_matcher.process(0.7)
                elif i == 4: # Youye Temperature
                    matched_chars['T'] = template_matcher.process(0.7)
                elif i == 5: # System Flow
                    matched_chars['Q'] = template_matcher.process(0.7)

                # print(matched_chars)
                
                
            # 将匹配结果放入消息队列  
            message_frame = convert_to_message_frame(matched_chars)  
  
            # 发送消息帧  
            client.send_message(message_frame)  
            print(f'Send successfully to {ip} {message_frame}')

            # break
              
            # 显示处理后的帧 
            # cv2.imshow('Processed Frame', thresholded_frame)  
              
            # # 按'q'键退出循环  
            # if cv2.waitKey(1) & 0xFF == ord('q'):  
            #     break  
    finally:  
        # 释放资源  
        cap.release()  
        cv2.destroyAllWindows()  


# 将匹配结果转换为消息帧  
def convert_to_message_frame(matched_chars):  
    message_frame = f"DATA:{matched_chars['SN']},P_0:{matched_chars['P_0']},P_1:{matched_chars['P_1']},T:{matched_chars['T']},Q_0:{matched_chars['Q_0']}".encode('utf-8')  
    return message_frame  
  
  
# # TCP客户端线程  
# def tcp_client_thread(ip='192.168.121.130', port=8900, matched_chars=None):  
#     client = TCPClient(ip, port)  
#     while True:  
#         # 尝试连接  
#         if not client.connected:  
#             client.connect()  
  
#         # 转换匹配结果为消息帧  
#         message_frame = convert_to_message_frame(matched_chars)  
  
#         # 发送消息帧  
#         client.send_message(message_frame)  
#         print(f'Send successfully to {ip} {message_frame}')
  
# 主程序入口  
if __name__ == "__main__":  
    # 初始化消息队列  
    # result_queue = MaxSizeQueue(10)
    # result_queue = queue.Queue()  
  
    # 创建线程1来处理视频流  
    ip = '192.168.3.26'
    port = 8900 
    process_video_stream_thread(ip, port)  
  
  
    # # 创建TCP客户端线程  

    # tcp_client_thread_obj = threading.Thread(target=tcp_client_thread, args=(ip, port, result_queue))  
    # tcp_client_thread_obj.start()  
  
    # # 主线程可以继续执行其他任务，比如从相机捕获帧和处理匹配结果  
    # # ...  
  
    # # 当需要停止程序时，可以优雅地关闭线程和连接  
    # video_thread.join()
    # tcp_client_thread_obj.join()  

    # # clear the queue

